package com.lbd.gulimall.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lbd.common.constrant.CommonAuthConstrant;
import com.lbd.common.to.GiteeSocialUser;
import com.lbd.common.utils.HttpUtils;
import com.lbd.common.utils.R;
import com.lbd.common.constrant.GiteeConstrant;
import com.lbd.gulimall.auth.feign.MemberFeignService;
import com.lbd.gulimall.auth.properties.Oauth2Properties;
import com.lbd.common.to.MemberEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: linbd
 * @Description:
 * @Date: 2023/3/19 1:17
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    private Oauth2Properties oauth2Properties;
    @Autowired
    private MemberFeignService memberFeignService;

    //码云授权成功的回调地址。第三方会返回code授权码给回调接口
    @GetMapping("/oauth2.0/gitee/success")
    public String success(@RequestParam("code") String code, HttpSession session) {
        log.info("授权成功的回调...");
        //根据code获取access_token
        //构建申请token的请求体
        Map<String, String> body = new HashMap<>();
        body.put("grant_type", "authorization_code");
        body.put("code", code);
        body.put("client_id", oauth2Properties.getClientId());
        body.put("client_secret", oauth2Properties.getClientSecret());
        body.put("redirect_uri", oauth2Properties.getRedirectUri());
        try {
            //获取access_token
            HttpResponse httpResponse = HttpUtils.doPost(GiteeConstrant.address, GiteeConstrant.path, "post", new HashMap<>(), new HashMap<>(), body);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(httpResponse.getEntity());
                GiteeSocialUser socialUser = JSONObject.parseObject(json, GiteeSocialUser.class);
                //调用远程服务进行第三方登录操作
                R r = memberFeignService.socialLogin(socialUser);
                if (r.getCode() == 0) {
                    MemberEntity member = r.getData(new TypeReference<MemberEntity>() {
                    });
                    //使用SpringSession在redis中存取session信息
                    session.setAttribute(CommonAuthConstrant.LOGIN_USER, member);
                    return "redirect:http://gulimall.com";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    String msg = r.getData("msg", new TypeReference<String>() {
                    });
                    errors.put("msg", msg);
                    session.setAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                String msg = "获取access_token失败...";
                log.error(msg);
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", msg);
                session.setAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", "获取access_token失败...");
            session.setAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    //发起跳转，让用户去第三方授权页面主动进行授权
    @GetMapping("/beginOauth2")
    public String beginOauth2() {
        log.info("Oauth2Properties => {}", oauth2Properties);
        String url = String.format("https://gitee.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code", oauth2Properties.getClientId(), oauth2Properties.getRedirectUri());
        return "redirect:" + url;
    }
}
